<template>
  <a-modal
    v-model:visible="visible"
    title="新增菜单"
    @ok="handleOk"
    ok-text="确定"
    cancel-text="取消"
  >
    <a-form
      ref="formRef"
      :model="modelRef"
      :rules="rulesRef"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="菜单名称" name="name">
        <a-input v-model:value="modelRef.name" />
      </a-form-item>
      <a-form-item label="上级菜单" name="pid">
        <a-tree-select
          :dropdown-style="{ maxHeight: '350px', overflow: 'auto' }"
          v-model:value="modelRef.pid"
          :tree-data="menuTree"
          :replaceFields="fieldNames"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="菜单路径" name="path">
        <a-input v-model:value="modelRef.path" />
      </a-form-item>
      <a-form-item label="排序" name="sort">
        <a-input-number v-model:value="modelRef.sort" />
      </a-form-item>
      <a-form-item label="是否隐藏" name="is_hide">
        <a-switch v-model:checked="modelRef.is_hide" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { addMenu } from "@/api/menu/shops/List";
import { toRefs, toRaw, reactive, nextTick, defineComponent } from "vue";
import { notice } from "@/config";
export default defineComponent({
  setup(props, { emit }) {
    let state = reactive({
      visible: false,
      menuTree: [],
      fieldNames: {
        children: "children",
        label: "name",
        key: "shops_menu_id",
        value: "shops_menu_id",
      },
      formRef: {},
    })
    let modelRef = reactive({
      name: "",
      pid: 0,
      path: "-",
      sort: 100,
      is_hide:false,
    })
    let rulesRef = reactive({
      name: [
        {
          required: true,
          message: "请输入菜单名称",
        },
      ],
      pid: [
        {
          required: true,
          message: "请选择菜单上级",
        },
      ],
      path: [
        {
          required: true,
          message: "请输入菜单路径",
        },
      ],
      sort: [
        {
          required: true,
          message: "请输入排序值",
        },
      ],
    })
    // 显示对话框
    const show = (menuTree) => {
      // 显示窗口
      state.visible = state.visible ? false : true
      state.menuTree = [{ shops_menu_id: 0, name: "顶级菜单" }, ...menuTree]
      nextTick(() => {
        state.formRef.resetFields()
      })
    }

    const handleOk = () => {
      state.formRef.validate().then(() => {
        addMenu(toRaw(modelRef)).then((res) => {
          emit("okCallback", res)
          notice(res.status == 200 ? "success" : "error", res.message)
          state.visible = false
        })
      })
    }

    return {
      show,
      handleOk,
      ...toRefs(state),
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 16,
      },
      modelRef,
      rulesRef,
    }
  },
})
</script>
